<template>
  <!-- 修改材料对话框 -->
  <el-dialog v-model="visible" title="修改施工明细" width="500px" @close="close" destroy-on-close>
    <el-form ref="commodityUpdateRef" :model="commodityUpdate" :rules="rules" label-position="right" label-width="100px">

      <el-row>
        <el-form-item label="项目名" prop="contractId">
          <el-input v-model="oldCommodity.contract.contractName" />
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="施工位置" prop="locationId">
          <el-select placeholder="请选择位置" v-model="commodityUpdate.locationId" allow-create clearable @change="changeLocation" filterable
            :reserve-keyword="false">
            <el-option v-for="t of location" :label="t.locationName" :value="t.id" :key="t.id"></el-option>
          </el-select>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item label="施工类型" prop="constructionTypeId">
          <el-select placeholder="请选择类型" v-model="commodityUpdate.constructionTypeId" clearable @change="changeType">
            <el-option v-for="t of type" :label="t.constructionType" :value="t.id" :key="t.id"></el-option>
          </el-select>
        </el-form-item>
      </el-row>

      <el-row>
        <el-form-item :label="newType.measurement + '(' + newType.unitName + ')'" prop="number">
          <el-input v-model="commodityUpdate.number" />
        </el-form-item>
      </el-row>

      <div v-if="showType">
        <el-row>
          <el-form-item label="所用产品：" prop="productId">
            <el-select placeholder="请选择产品" v-model="commodityUpdate.productId" clearable>
              <el-option v-for="store of stores" :label="store.productName" :value="store.productId"
                :key="store.productId"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item :label="newType.measurementProduct + '(' + newType.unitProductName + ')'" prop="numberProduct">
            <el-input v-model="commodityUpdate.numberProduct" />
          </el-form-item>
        </el-row>
      </div>

      <el-row>
        <el-form-item label="天气" prop="measurementProduct">
          <el-input v-model="commodityUpdate.measurementProduct" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="commodityUpdate.remark" />
        </el-form-item>
      </el-row>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="updateCommodity">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { put, tip, WAREHOUSE_CONTEXT_PATH, get } from "@/common"
import { Plus } from '@element-plus/icons-vue'

// 该页面的可见性
const visible = ref(false);
// 图片回显路径
const imageUrl = ref('');

// 添加文件时的回显
const handleAvatarChange = (uploadFile) => {
  const reader = new FileReader();
  // 从上传组件中获取数据
  const image = uploadFile.raw;
  reader.readAsDataURL(image);
  // 读取文件的回调函数
  reader.onload = () => {
    // 将转化的url赋值给文件
    imageUrl.value = reader.result;
    commodityUpdate.imgs = image.name;
  };
}

// 上传之前做简单验证
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpg'
    && rawFile.type !== 'image/jpeg'
    && rawFile.type !== 'image/png'
    && rawFile.type !== 'image/gif'
    && rawFile.type !== 'image/svg'
    && rawFile.type !== 'image/webp'
  ) {
    tip.error('只能上传图片格式!');
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    tip.error('上传文件不能大于5MB!');
    return false
  }
  return true
}

// 修改材料对象
const commodityUpdate = reactive({
  contractName: '',
  contractId: '',
  dailyConstructionId: '',
  date: '',
  locationId: '',
  newLocationName:'',
  newLocationName: '',
  constructionTypeId: '',
  productId: '',
  weather: '',
  number: '',
  numberProduct: '',
  remark: '',
});
const oldCommodity = ref();

// 表单验证规则
const rules = reactive({
  constructionType: [
    { required: true, message: '请输入名称', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请选择单位', trigger: 'blur' }
  ],
  measurement: [
    { required: true, message: '请输入计量名称', trigger: 'blur' }
  ],
  // productNum: [
  //   { required: true, message: '请输入材料编号', trigger: 'blur' }
  // ],
  // supplyId: [
  //   { required: true, message: '请选择供应商', trigger: 'blur' }
  // ],
  // placeId: [
  //   { required: true, message: '请选择产地', trigger: 'blur' }
  // ],
  // unitId: [
  //   { required: true, message: '请选择单位', trigger: 'blur' }
  // ],
})

// 关闭
const close = () => {
  visible.value = false;
}

// 所有仓库
const stores = ref();
// 所有品牌
const brands = ref();
// 所有分类
const categorys = ref();
// 所有供应商
const supplys = ref();
// 所有产地
const places = ref();
// 所有单位
const units = ref();

// 树形结构数据对应实体类属性
const defaultProps = {
  children: 'childGoodsCategory',
  label: 'typeName',
}

// 该对话框打开，进行数据初始化
const open = (commodity, storeList, unitList, typeList) => {
  getType();
  getLocation();
  oldCommodity.value = commodity
  commodityUpdate.locationId = commodity.locationId
  commodityUpdate.constructionTypeId = commodity.constructionTypeId
  commodityUpdate.productId = commodity.productId
  commodityUpdate.number = commodity.constructionDetails.number
  commodityUpdate.productId = commodity.productId
  commodityUpdate.numberProduct = commodity.constructionDetails.numberProduct
  commodityUpdate.remark = commodity.constructionDetails.remark
  commodityUpdate.weather = commodity.constructionDetails.weather
  commodityUpdate.dailyConstructionId = commodity.id

  stores.value = storeList.value;
  units.value = unitList.value;
  type.value = typeList.value;
  visible.value = true;
  if (typeList.length < 1) {
    newType.value = {
      measurement: "无施工类型",
      unitProductName: "无施工类型"
    }
  } else {
    newType.value = type.value[0];
  }

  console.log(oldCommodity.value)
};


const location = ref();
// 获得所有位置
const getLocation = () => {
  get("/location/location-list/" + commodityUpdate.contractId).then(result => {
    location.value = result.data;
  })
};
const newType = ref();
// 获得所有类型
const type = ref();
const getType = () => {
  get("/constructionType/constructionType-list/" + commodityUpdate.contractId).then(result => {
    type.value = result.data;

    if (type.length < 1) {
      newType.value = {
        measurement: "无施工类型",
        unitProductName: "无施工类型"
      }
    } else {
      newType.value = type.value[0];
    }
  })
};

const commodityUpdateRef = ref();
// 定义
const emit = defineEmits(["ok"]);
// 添加材料提交
const updateCommodity = () => {
  if(typeof commodityUpdate.locationId.value != 'number'){
    commodityUpdate.newLocationName = commodityUpdate.locationId
    commodityUpdate.locationId = ''
  }
  commodityUpdateRef.value.validate(valid => {
    if (valid) {
      put('/construction/update', commodityUpdate).then(result => {
        emit('ok');
        tip.success(result.message);
        visible.value = false; // 关闭对话框
      });
    }
  });
}

// 产品输入是否显示
const showType = ref();
// 选择施工类型，改变输入
const changeType = () => {
  newType.value = type.value.find(t => t.id == commodityAdd.constructionTypeId)
  if (newType.value.productId != null) {
    showType.value = true;
  } else {
    showType.value = false;
  }
}

defineExpose({ open });
</script>

<style scoped>
.avatar-uploader,
.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
</style>